<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useAuth } from '@/hooks/business/auth';
import { $t } from '@/locales';

defineOptions({
  name: 'TableHeaderOperation'
});

interface Props {
  itemAlign?: NaiveUI.Align;
  disabledDelete?: boolean;
  loading?: boolean;
  createAuth?: string;
  deleteAuth?: string;
  createShow?: string;
  deleteShow?: string;
  createText?: string;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'add'): void;
  (e: 'delete'): void;
  (e: 'refresh'): void;
}

const emit = defineEmits<Emits>();
const { hasAuth } = useAuth();

const columns = defineModel<NaiveUI.TableColumnCheck[]>('columns', {
  default: () => []
});

function add() {
  emit('add');
}

function batchDelete() {
  emit('delete');
}

function refresh() {
  emit('refresh');
}

const showCreateButton = ref(true);
const showDeleteButton = ref(true);
const createButtonText = ref('');
function init() {
  showCreateButton.value = props.createShow === undefined ? true : props.createShow === 'true';
  showDeleteButton.value = props.deleteShow === undefined ? true : props.deleteShow === 'true';
  createButtonText.value = props.createText === undefined ? $t('common.add') : props.createText;
}
onMounted(() => {
  init();
});
</script>

<template>
  <NSpace :align="itemAlign" wrap justify="end" class="lt-sm:w-200px">
    <slot name="prefix"></slot>
    <slot name="default">
      <NButton v-if="hasAuth(createAuth as string) && showCreateButton" size="small" ghost type="primary" @click="add">
        <template #icon>
          <icon-ic-round-plus class="text-icon" />
        </template>
        {{ createButtonText }}
      </NButton>
      <NPopconfirm v-if="hasAuth(deleteAuth as string) && showDeleteButton" @positive-click="batchDelete">
        <template #trigger>
          <NButton size="small" ghost type="error" :disabled="disabledDelete">
            <template #icon>
              <icon-ic-round-delete class="text-icon" />
            </template>
            {{ $t('common.batchDelete') }}
          </NButton>
        </template>
        {{ $t('common.confirmDelete') }}
      </NPopconfirm>
    </slot>
    <NButton size="small" @click="refresh">
      <template #icon>
        <icon-mdi-refresh class="text-icon" :class="{ 'animate-spin': loading }" />
      </template>
      {{ $t('common.refresh') }}
    </NButton>
    <TableColumnSetting v-model:columns="columns" />
    <slot name="suffix"></slot>
  </NSpace>
</template>

<style scoped></style>
